﻿﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using System.Xml.Linq;
using System.Threading;
using System.Threading.Tasks;

using iShangMai.Models.Weixin;

using Senparc.Weixin.MP.Entities.Request;
using Senparc.Weixin.MP.MessageHandlers;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities;
using Senparc.Weixin.MP.Helpers;
using Senparc.Weixin.MP.MvcExtension;

using BartonExtension;
using ResponseObject;
using SQLWrapper;
using Utils;

namespace iShangMai.Controllers
{
    public class WeixinInterfaceController : Controller
    {
        public static readonly string token = ConfigurationExtensions.ValueOfConfig("weixin_token");
        public static readonly string encodeAESKey = ConfigurationExtensions.ValueOfConfig("weixin_encoding_key");
        public static readonly string appId = ConfigurationExtensions.ValueOfConfig("weixin_app_id");

        public WeixinInterfaceController()
        {

        }

        [HttpGet]
        public ActionResult WexinValidator(string signature, string timestamp, string nonce, string echostr)
        {
            if(CheckSignature.Check(signature,timestamp,nonce,token))
            {
                return Content(echostr);
            }
            else
            {
                return Content("failed:" + signature + "," + CheckSignature.GetSignature(timestamp, nonce, token) + "。" +
                    "如果你在浏览器中看到这句话，说明此地址可以被作为微信公众账号后台的Url，请注意保持Token一致。");
            }
        }

        [HttpGet]
        public FixWeixinBugWeixinResult Post(PostModel model)
        {
            if (!CheckSignature.Check(model.Signature, model.Timestamp, model.Nonce, token))
            {
                return new FixWeixinBugWeixinResult("参数错误");
            }

            model.Token = token;
            model.EncodingAESKey = encodeAESKey;
            model.AppId = appId;

            var maxRecordCount = ConfigurationExtensions.ValueOfConfig("max_record_count").toInt32().Value;
            var messageHandler = new FKMessageHandler(Request.InputStream,model,maxRecordCount);
            
            try
            {
                if(!Directory.Exists(Server.MapPath("~/logs/")))
                {
                    Directory.CreateDirectory(Server.MapPath("~/logs/"));
                }

                messageHandler.RequestDocument.Save(Server.MapPath("~/logs/" + DateTime.Now.Ticks + "_Request_" + messageHandler.RequestMessage.FromUserName + ".txt"));
                if (messageHandler.UsingEcryptMessage)
                {
                    messageHandler.EcryptRequestDocument.Save(Server.MapPath("~/logs/" + DateTime.Now.Ticks + "_Request_Ecrypt_" + messageHandler.RequestMessage.FromUserName + ".txt"));
                }
                messageHandler.OmitRepeatedMessage = true;

                messageHandler.Execute();

                if (messageHandler.ResponseDocument != null)
                {
                    messageHandler.ResponseDocument.Save(Server.MapPath("~/logs/" + DateTime.Now.Ticks + "_Response_" + messageHandler.ResponseMessage.ToUserName + ".txt"));
                }

                if (messageHandler.UsingEcryptMessage)
                {
                    //记录加密后的响应信息
                    messageHandler.FinalResponseDocument.Save(Server.MapPath("~/logs/" + DateTime.Now.Ticks + "_Response_Final_" + messageHandler.ResponseMessage.ToUserName + ".txt"));
                }

                return new FixWeixinBugWeixinResult(messageHandler);
            }
            catch(Exception ex)
            {
                using (TextWriter tw = new StreamWriter(Server.MapPath("~/logs/Error_" + DateTime.Now.Ticks + ".txt")))
                {
                    tw.WriteLine("ExecptionMessage:" + ex.Message);
                    tw.WriteLine(ex.Source);
                    tw.WriteLine(ex.StackTrace);
                    //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message);

                    if (messageHandler.ResponseDocument != null)
                    {
                        tw.WriteLine(messageHandler.ResponseDocument.ToString());
                    }

                    if (ex.InnerException != null)
                    {
                        tw.WriteLine("========= InnerException =========");
                        tw.WriteLine(ex.InnerException.Message);
                        tw.WriteLine(ex.InnerException.Source);
                        tw.WriteLine(ex.InnerException.StackTrace);
                    }

                    tw.Flush();
                    tw.Close();
                }
                return new FixWeixinBugWeixinResult("");
            }
        }
    }
}
